<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\WorkMoment\Action\Dashboard;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\Rbac\Middleware\PermissionMiddleware;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\WorkMoment\Contract\WorkMomentContract;
use MoChat\Plugin\WorkMoment\Contract\WorkMomentEmployeeContract;

/**
 * 企微朋友圈-详情.
 *
 * Class Index.
 * @Controller
 */
class Show extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeContract;

    /**
     * @Inject
     * @var WorkMomentEmployeeContract
     */
    protected $workMomentEmployeeContract;

    /**
     * @Inject
     * @var WorkMomentContract
     */
    private $workMomentContract;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/workMoment/show", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        # # 判断用户绑定企业信息
        if (! isset($user['corpIds']) || count($user['corpIds']) !== 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        # # 验证参数
        $this->validated($this->request->all());
        # # 接收参数
        $params = [
            'type' => (int) $this->request->input('type', 1),
            'id' => (int) $this->request->input('id', 0),
            'employeeName' => $this->request->input('employeeName', ''),
            'employeeType' => (int) $this->request->input('employeeType', 2),
        ];

        if ($params['type'] === 1) {
            return [
                'info' => $this->info($params),
                'employees' => $this->employees($params),
            ];
        }

        if ($params['type'] === 2) {
            return [
                'info' => $this->info($params),
            ];
        }

        return [];
    }

    /**
     * 朋友圈详情.
     */
    protected function info(array $params): array
    {
        $info = $this->workMomentContract->getWorkMomentById($params['id'], ['id', 'employee_id', 'create_type', 'create_time', 'text', 'image', 'video', 'link']);

        $info['createTime'] = date('Y-m-d H:i:s', (int) $info['createTime']);
        # # 文字
        if (! empty(Json::decode($info['text']))) {
            $info['contentType'] = '文字';
        }
        # # 图片
        if (! empty(Json::decode($info['image']))) {
            $info['contentType'] = '图片';
            $images = Json::decode($info['image']);
            foreach ($images as $imageKey => $imageVal) {
                $images[$imageKey]['image'] = file_full_url($imageVal['image']);
            }
            $info['image'] = $images;
        }
        # # 视频
        if (! empty(Json::decode($info['video']))) {
            $info['contentType'] = '视频';
            $videos = Json::decode($info['video']);
            $videos['video'] = file_full_url($videos['video']);
            $info['video'] = $videos;
        }
        # # 链接
        if (! empty(Json::decode($info['link']))) {
            $info['contentType'] = '链接';
            $info['link'] = Json::decode($info['link']);
        }
        # # 创建人
        $creator = $this->workEmployeeContract->getWorkEmployeeById($info['employeeId'], ['name']);
        $info['creator'] = $creator['name'] ?? '';
        return $info;
    }

    /**
     * 发送成员详情.
     */
    protected function employees(array $params): array
    {
        $data = [
            'total' => $this->workMomentEmployeeContract->countWorkMomentEmployeeByMomentIdPublishStatus($params['id'], 2),
            'send' => $this->workMomentEmployeeContract->countWorkMomentEmployeeByMomentIdPublishStatus($params['id'], 1),
            'noSend' => $this->workMomentEmployeeContract->countWorkMomentEmployeeByMomentIdPublishStatus($params['id'], 0),
        ];
        if ($params['employeeType'] === 2) {
            $momentEmployee = $this->workMomentEmployeeContract->getWorkMomentEmployeeByMomentId($params['id'], ['publish_status', 'employee_id']);
        } else {
            $momentEmployee = $this->workMomentEmployeeContract->getWorkMomentEmployeeByMomentIdPublishStatus($params['id'], $params['employeeType'], ['publish_status', 'employee_id']);
        }
        foreach ($momentEmployee as $k => $v) {
            $employee = $this->workEmployeeContract->getWorkEmployeeById($v['employeeId'], ['name', 'avatar']);
            $momentEmployee[$k]['name'] = $employee['name'] ?? '';
            $momentEmployee[$k]['avatar'] = empty($employee['avatar']) ? '' : file_full_url($employee['avatar']);
            if (! empty($params['employeeName']) && ! str_contains($momentEmployee[$k]['name'], $params['employeeName'])) {
                unset($momentEmployee[$k]);
            }
        }
        $data['employees'] = array_merge($momentEmployee);
        return $data;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'type' => 'required',
            'id' => 'required',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'type.required' => 'type 必传',
            'id.required' => 'id 必传',
        ];
    }
}
